package com.eso.frame.task.job;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * 定时任务运行状态管理实现类
 * User: Noah.Rong
 * Version: 0.1,  2012-05-22 15:48
 */
@Component
public class ExecutingJobsManager implements RunningJobManager {
    private Set<Object> executingJobs = new HashSet<Object>();
    private int numJobsFired = 0;

    public String getName() {
        return this.getClass().getName();
    }

    public void jobToBeExecuted(JobExecutionContext context) {
        numJobsFired++;
        MethodInvokingJobDetailFactoryBean value = (MethodInvokingJobDetailFactoryBean) context.getJobDetail().getJobDataMap().get("methodInvoker");
        synchronized (executingJobs) {
            executingJobs.add(value.getTargetObject());
        }
    }

    public void jobExecutionVetoed(JobExecutionContext context) {

    }

    public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) {
        numJobsFired--;
        MethodInvokingJobDetailFactoryBean value = (MethodInvokingJobDetailFactoryBean) context.getJobDetail().getJobDataMap().get("methodInvoker");
        synchronized (executingJobs) {
            executingJobs.remove(value.getTargetObject());
        }
    }

    public Boolean isRunning(Object targetObject) {
        return executingJobs.contains(targetObject);
    }

    public void triggerRunningJobByHand(Object targetObject) {
        numJobsFired++;
        synchronized (executingJobs) {
            executingJobs.add(targetObject);
        }
    }

    public void perishRunningJobByHand(Object targetObject) {
        numJobsFired--;
        synchronized (executingJobs) {
            executingJobs.remove(targetObject);
        }
    }

    public Integer getNumJobsFired() {
        return numJobsFired;
    }
}
